<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑文档' : '新增文档'"
    width="80%"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="document-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="文档标题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入文档标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="文档类型" prop="docType">
            <el-select
              v-model="formData.docType"
              placeholder="请选择文档类型"
              style="width: 100%"
            >
              <el-option
                v-for="option in DOC_TYPE_OPTIONS"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="来源" prop="source">
            <el-input
              v-model="formData.source"
              placeholder="请输入文档来源"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="发布日期" prop="publishDate">
            <el-date-picker
              v-model="formData.publishDate"
              type="datetime"
              placeholder="请选择发布日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="关键词" prop="keywords">
        <el-input
          v-model="formData.keywords"
          placeholder="请输入关键词，多个关键词用逗号分隔"
          maxlength="200"
          show-word-limit
        />
        <div class="form-tip">多个关键词请用逗号分隔，如：合同,法律,民事</div>
      </el-form-item>
      
      <el-form-item label="标签" prop="tagIds">
        <el-select
          v-model="formData.tagIds"
          multiple
          filterable
          placeholder="请选择标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag.id"
            :label="tag.name"
            :value="tag.id"
          >
            <div class="tag-option">
              <el-tag
                :color="tag.color"
                :style="{ color: getTextColor(tag.color) }"
                size="small"
                class="tag-option-display"
              >
                {{ tag.name }}
              </el-tag>
              <span class="tag-usage-count">{{ tag.usageCount }}次</span>
            </div>
          </el-option>
        </el-select>
        <div class="form-tip">请选择已有标签</div>
      </el-form-item>
      
      <el-form-item label="文档文件" prop="fileUrl">
        <div class="file-upload-section">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="handleBeforeUpload"
            :limit="1"
            :file-list="fileList"
            accept=".pdf,.doc,.docx"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持格式：PDF、Word（.doc/.docx），文件大小不超过50MB
              </div>
            </template>
          </el-upload>
          
          <!-- 文件上传进度 -->
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
            <el-progress :percentage="uploadProgress" :stroke-width="8" />
            <span class="progress-text">正在上传... {{ uploadProgress }}%</span>
          </div>
          
          <!-- 已上传的文件信息 -->
          <div v-if="formData.fileUrl && !currentFile" class="uploaded-file-info">
            <div class="file-info-card">
              <el-icon class="file-icon"><DocumentCopy /></el-icon>
              <div class="file-details">
                <span class="file-name">{{ getFileNameFromUrl(formData.fileUrl) }}</span>
                <span class="file-type-badge">{{ getFileTypeFromUrl(formData.fileUrl) }}</span>
              </div>
              <el-button 
                type="danger" 
                size="small" 
                text 
                @click="handleRemoveUploadedFile"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="文档内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="15"
          placeholder="请输入文档内容"
          maxlength="50000"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, DocumentCopy, Delete } from '@element-plus/icons-vue'
import { createDocument, updateDocument, getDocumentDetail, DOC_TYPE_OPTIONS, uploadDocument } from '../../../api/document'
import { getAllTags } from '../../../api/tag'
import { validateDocumentFile, getFileType } from '../../../utils/upload'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  documentData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单引用
const formRef = ref()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否为编辑模式
const isEdit = computed(() => !!props.documentData?.id)

// 提交加载状态
const submitLoading = ref(false)

// 可用标签列表（从接口动态获取）
const availableTags = ref([])

// 文件上传相关
const uploadRef = ref()
const fileList = ref([])
const currentFile = ref(null)
const uploadProgress = ref(0)

// 表单数据
const formData = reactive({
  id: null,
  title: '',
  content: '',
  docType: null,
  publishDate: '',
  source: '',
  keywords: '',
  tagIds: [],
  fileUrl: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入文档标题', trigger: 'blur' },
    { max: 200, message: '文档标题不能超过200个字符', trigger: 'blur' }
  ],
  docType: [
    { required: true, message: '请选择文档类型', trigger: 'change' }
  ],
  publishDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  source: [
    { required: true, message: '请输入文档来源', trigger: 'blur' },
    { max: 100, message: '文档来源不能超过100个字符', trigger: 'blur' }
  ],
  keywords: [
    { max: 200, message: '关键词不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文档内容', trigger: 'blur' },
    { max: 50000, message: '文档内容不能超过50000个字符', trigger: 'blur' }
  ]
}

// 计算文字颜色（根据背景色深浅）
const getTextColor = (backgroundColor) => {
  if (!backgroundColor) return '#333'
  
  // 去掉#号
  const hex = backgroundColor.replace('#', '')
  
  // 转换为RGB
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 计算亮度
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  
  // 根据亮度返回黑色或白色文字
  return brightness > 128 ? '#333' : '#fff'
}

// 从URL中提取文件名
const getFileNameFromUrl = (url) => {
  if (!url) return '已上传文件'
  return url.substring(url.lastIndexOf('/') + 1)
}

// 从URL中提取文件类型
const getFileTypeFromUrl = (url) => {
  if (!url) return ''
  const fileName = url.substring(url.lastIndexOf('/') + 1)
  const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
  return fileType.toUpperCase()
}

// ==================== 文件上传相关函数 ====================

// 文件选择前的验证
const handleBeforeUpload = (file) => {
  const validation = validateDocumentFile(file)
  
  if (!validation.valid) {
    validation.errors.forEach(error => {
      ElMessage.error(error)
    })
    return false
  }
  
  return true
}

// 文件选择变化时
const handleFileChange = (file) => {
  const validation = validateDocumentFile(file.raw)
  
  if (!validation.valid) {
    validation.errors.forEach(error => {
      ElMessage.error(error)
    })
    fileList.value = []
    return
  }
  
  currentFile.value = file.raw
  fileList.value = [file]
  
  // 如果有旧文件，清除旧文件信息
  formData.fileUrl = ''
}

// 移除文件
const handleFileRemove = () => {
  currentFile.value = null
  fileList.value = []
  uploadProgress.value = 0
}

// 删除已上传的文件
const handleRemoveUploadedFile = () => {
  formData.fileUrl = ''
  currentFile.value = null
  fileList.value = []
  uploadProgress.value = 0
  ElMessage.success('文件已移除')
}

// 上传文件到服务器
const uploadFileToServer = async () => {
  if (!currentFile.value) {
    return true // 没有新文件需要上传
  }
  
  try {
    uploadProgress.value = 10
    
    const response = await uploadDocument(currentFile.value)
    
    uploadProgress.value = 100
    
    if (response.code === 200) {
      const fileData = response.data
      // 只保存 fileUrl
      formData.fileUrl = fileData.url
      
      ElMessage.success('文件上传成功')
      
      // 清空当前文件，但保留文件URL
      currentFile.value = null
      fileList.value = []
      
      return true
    } else {
      ElMessage.error(response.message || '文件上传失败')
      return false
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败，请重试')
    return false
  } finally {
    uploadProgress.value = 0
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const response = await getAllTags()
    if (response.code === 200) {
      availableTags.value = response.data
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    title: '',
    content: '',
    docType: null,
    publishDate: '',
    source: '',
    keywords: '',
    tagIds: [],
    fileUrl: ''
  })
  currentFile.value = null
  fileList.value = []
  uploadProgress.value = 0
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 如果有新文件需要上传，先上传文件
    if (currentFile.value) {
      const uploadSuccess = await uploadFileToServer()
      if (!uploadSuccess) {
        submitLoading.value = false
        return
      }
    }
    
    const submitData = { ...formData }
    
    let response
    if (isEdit.value) {
      response = await updateDocument(submitData)
    } else {
      // 新增时删除id字段
      delete submitData.id
      response = await createDocument(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 监听文档数据变化，填充表单
watch(() => props.documentData, async (newData) => {
  if (newData) {
    // 如果是编辑模式，需要获取详细信息
    if (newData.id) {
      try {
        const response = await getDocumentDetail(newData.id)
        if (response.code === 200) {
          const detailData = response.data
          Object.assign(formData, {
            id: detailData.id,
            title: detailData.title,
            content: detailData.content,
            docType: detailData.docType,
            publishDate: detailData.publishDate,
            source: detailData.source,
            keywords: detailData.keywords,
            tagIds: detailData.tags ? detailData.tags.map(tag => tag.id) : [],
            fileUrl: detailData.fileUrl || ''
          })
        }
      } catch (error) {
        console.error('获取文档详情失败:', error)
        ElMessage.error('获取文档详情失败')
      }
    } else {
      // 新增模式直接使用传入的数据
      Object.assign(formData, {
        id: null,
        title: newData.title || '',
        content: newData.content || '',
        docType: newData.docType || null,
        publishDate: newData.publishDate || '',
        source: newData.source || '',
        keywords: newData.keywords || '',
        tagIds: [],
        fileUrl: ''
      })
    }
  }
}, { immediate: true })

// 监听对话框打开，重置表单并获取标签
watch(dialogVisible, (visible) => {
  if (visible) {
    fetchTags()
  } else {
    resetForm()
  }
})

// 组件挂载时获取标签列表
onMounted(() => {
  fetchTags()
})
</script>

<style scoped>
.document-form {
  padding: 0 20px;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

.tag-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.tag-option-display {
  border: none;
  font-weight: 600;
}

.tag-usage-count {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

/* 文件上传部分 */
.file-upload-section {
  width: 100%;
}

.upload-progress {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.progress-text {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.uploaded-file-info {
  margin-top: 15px;
}

.file-info-card {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  gap: 12px;
}

.file-icon {
  font-size: 32px;
  color: #409eff;
}

.file-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.file-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  word-break: break-all;
}

.file-type-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: #409eff;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  border-radius: 3px;
  width: fit-content;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  line-height: 1.6;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-upload-dragger) {
  padding: 30px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #409eff;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-form {
    padding: 0 10px;
  }
  
  :deep(.el-col) {
    margin-bottom: 15px;
  }
  
  .file-info-card {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
